<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div>
            <span>全选:</span>
            <!-- 
                @change事件只在用户直接与复选框交互时触发
            -->
            <input type="checkbox" v-model="isCheckAll" @change="selectAll" />
            <button @click="selectFan">反选</button>
            <ul>
                <li v-for="(item,index) in arr" :key="index">
                    <input type="checkbox" v-model="item.checked" />
                    <span>{{ item.name }}</span>
                </li>
            </ul>
        </div>
    </div>
    <script src="../js/vue.js"></script>
    <script>
        const app = new Vue({
            el: '#app',
            data: {
                arr: [
                    {
                        name: "猪八戒",
                        checked: false,
                    },
                    {
                        name: "孙悟空",
                        checked: false,
                    },
                    {
                        name: "唐僧",
                        checked: false,
                    },
                    {
                        name: "白龙马",
                        checked: false,
                    },
                ],
                isCheckAll: false,
            },
            methods: {
                selectAll() {
                    // console.log(this.isCheckAll)
                    this.arr.forEach(item => item.checked = this.isCheckAll)
                },
                selectFan() {
                    this.isCheckAll = !this.isCheckAll
                    this.selectAll()
                }
            },
            watch: {
                arr: {
                    deep: true,
                    immediate: true,
                    handler() {
                        this.isCheckAll = this.arr.every(item => item.checked)
                    }
                }
            }

            // 另外的方法
            //     computed: {
            //         isCheckAll: {
            //             get() {
            //                 return this.arr.every(item => item.checked)
            //             },
            //             set(newValue) {
            //                 this.arr.forEach(item => item.checked = newValue)
            //             }
            //         }
            //     },
            //     methods: {
            //         selectFan() {
            //             this.isCheckAll = !this.isCheckAll
            //         }
            //     }
        })
    </script>


</body>

</html>